<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
/**
 * 充值相关操作Controller
 */
namespace AuctionBack\Controller;


use AuctionBack\Controller\BaseController;
use AuctionBack\Service\AlipayService;
use AuctionBack\Service\ThriftBailService;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarDealer\Recharge;
use AuctionCore\CarResource\DealerRepairPayLog;
use AuctionCore\Common\PhpRedis;
use AuctionCore\System\SystemConf;
use AuctionCore\CarDealer\Dealer;
use Common\Lib\Lakala\Lakala;
use Think\Log;

class PayResultController extends BaseController
{

	public function __construct()
	{
		parent::__construct();
		$alipayConf = SystemConf::getConfByName("ALIPAY_CONFIG");
		$this->alipayConf = json_decode($alipayConf['value'],true);
	}

	//加载充值页面
	public function index()
	{
		$this->display();
	}

	public function pay_trade_query(){
		$type= I('post.type');
		$out_trade_no = I('post.out_trade_no');
		$out_trade_no = trim($out_trade_no);
		if(empty($out_trade_no)){
			$this->helpJsonResult(500, "商户订单号不能为空");
		}
		if(empty($type)){
			$this->helpJsonResult(500, "状态异常，请刷新页面后重试");
		}
		//锁定
		self::unlockOrder($out_trade_no);
		$is_lock = self::lockOrder($out_trade_no);
		if(!$is_lock){
			$this->helpJsonResult(500, "状态异常，请刷新页面后重试");
		}
		//通过out_trade_no 获取订单信息
		$order_msg = Recharge::getByOrderNo($out_trade_no);
		//查询不到订单返回失败状态
		if(empty($order_msg)){
			self::unlockOrder($out_trade_no);
			$this->helpJsonResult(500, "查询不到订单信息");
		}
		//判断是否已充值成功
		if($order_msg['pay_result']==1){
			self::unlockOrder($out_trade_no);
			$this->helpJsonResult(500, "订单已支付成功");
		}
		$d = new Dealer($order_msg['dealer_id']);
		$dealer_info = $d->detail();
		$branch_id = $dealer_info['depart_id'];
		if($type==2){//支付宝查询
			//获取alipayconfig
			$alipay_user = $this->alipayConf[$branch_id];
			$state = AlipayService::check_trade($out_trade_no,'',$alipay_user);
			if(!$state){
				self::unlockOrder($out_trade_no);
				$this->helpJsonResult(500, "第三方未查询到此订单信息");
			}
			//验证参数正确定性
			if( intval($state['alipay_trade_query_response']['total_amount']) != intval($order_msg['amount']) ){
				self::unlockOrder($out_trade_no);
				$this->helpJsonResult(500, "订单金额异常，请联系技术人员");
			}
			//验证订单支付状态
			if($state['alipay_trade_query_response']['trade_status']=='TRADE_SUCCESS'){
				/**用户充值**/
				$trade_no = $state['alipay_trade_query_response']['trade_no'];
				$pay_time = $state['alipay_trade_query_response']['send_pay_date'];
				//用户充值
				$this->public_dealer_recharge($out_trade_no,$trade_no,$order_msg,$state,$order_msg['dealer_id'],$branch_id,2,$pay_time);
			}else{
				self::unlockOrder($out_trade_no);
				info_log('Alipay/Error',json_encode(array('金额异常'=>$state)));
				$this->helpJsonResult(500, "订单金额异常");
			}
		}else{//拉卡拉查询
			$laka = new Lakala();
			$result = $laka->query_order($out_trade_no);
			if(!$result){
				self::unlockOrder($out_trade_no);
				$this->helpJsonResult(500, "请求异常，请稍后重试");
			}
			$res = $laka->decryptReqData($result);
			if ($res['status'] == 1 && $res['data']['payResult'] == 1) {
				$pay_time = date('Y-m-d H:i:s',strtotime($res['data']['orderTime']));
				$this->public_dealer_recharge($out_trade_no,$res['data']['transactionId'],$order_msg,$res,$order_msg['dealer_id'],$branch_id,1,$pay_time);
			}else{
				$this->helpJsonResult(500, $result['retMsg']);
				Log::record($res['error'], 'ERR', true);
				exit;
			}
		}
	}

	/**订单上锁
	 * @param $out_trade_no
	 * @return bool
	 */
	public static function lockOrder($out_trade_no){
		$redis = new PhpRedis();
        $arr = [
            'out_trade_no'=>$out_trade_no,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100004',$arr);
        return $redis->lock($keyName);
		//return $redis->lock($out_trade_no.'_order_status');
	}

	/**解锁订单
	 * @param $out_trade_no
	 */
	public static function  unlockOrder($out_trade_no){
		$redis = new PhpRedis();
        $arr = [
            'out_trade_no'=>$out_trade_no,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100004',$arr);
        $redis->unlock($keyName);
		//$redis->unlock($out_trade_no.'_order_status');
	}

	/**
	 * 公共操作方法
	 * @param $out_trade_no   商户订单号
	 * @param $trade_no       第三方订单号
	 * @param $order_info     订单信息
	 * @param $data			  请求第三方返回结果
	 * @param $dealer_id      车商ID
	 * @param $branch_id      车商经营城市ID
	 * @param $pay_method     付款方式
	 * @param $pay_time       支付时间
	 */
	private  function public_dealer_recharge($out_trade_no,$trade_no,$order_info,$data,$dealer_id,$branch_id,$pay_method,$pay_time){
		$charge = new Recharge($dealer_id);
		//修改订单成功状态
		$data = array(
				'third_party'=>empty($pay_method)?2:$pay_method,
				'pay_result'=>1,
				'ret_msg'=>json_encode($data),
				'transaction_id'=>$trade_no,
				'deal_time'=>$pay_time,
				'branch_id'=>$branch_id
		);
		M()->startTrans();
		$result = $charge->upByOrderNo($out_trade_no,$data);
		$Asset = new AssetCenter($order_info['dealer_id']);
		$option = array(
				'occur_money'=>$order_info['amount'],
				'use_detail'=>"保证金充值[" . $out_trade_no . "]",
				'recharge_method'=>$pay_method,
				'recharge_id'=>$order_info['id'],
				'recharge_no'=>$out_trade_no,
				'emp_id'=>'1',
				'emp_name'=>'系统'
		);
		$res = $Asset->bail_recharge($option);
//		$res = $Asset->bail_rechange($order_info['amount'], 1, "保证金充值[" . $out_trade_no . "]",$out_trade_no,$order_info['id']);
		if (!$res || !$result) {
			Log::record("车商: [ {$order_info['dealer_id']} ],充值: [ {$order_info['amount']} ], 失败", 'ERR', true);
			M()->rollback();
		}
		Log::record("车商: [ {$order_info['dealer_id']} ],充值: [ {$order_info['amount']} ], 成功", 'INFO', true);
		M()->commit();
		self::unlockOrder($out_trade_no);
		//检测是否有透支情况
		$this->check_minus($dealer_id);
		$this->helpJsonResult(200, "查询成功，已完成用户充值操作");
	}

	/**     * @param $dealer_id
	 */
	private function check_minus($dealer_id){
		$credit_lines = SystemConf::getConfByName("REPAIR_CREDIT_LINES");
		$single_price = SystemConf::getConfByName("REPAIR_SINGL_PRICE");
		$credit_lines = $credit_lines['value'];
		$single_price = $single_price['value'];
		$use_type=8;
		$dealer_bail = true;

		$d = new Dealer($dealer_id);
		$dealer_info = $d->detail();

		$minus_amount = $dealer_info['minus_amount'];
		if($minus_amount==$credit_lines && $dealer_info['bail_amount']>=$single_price){
			$dealer = new Dealer($dealer_id);
			$pay_log = new DealerRepairPayLog($dealer_id);
			$last_amount = $log_list = 0;
			$usemoney = $minus_amount;
			$bail_amount = $dealer_info['bail_amount']-$minus_amount;

			//判断充值后余额是否大于维保透支
			if($dealer_info['bail_amount']<$minus_amount){
				//计算修改状态日志条数
				$log_list = intval($dealer_info['bail_amount']/$single_price);
				$last_amount = $minus_amount-($single_price*$log_list);
				$bail_amount = intval(fmod(floatval($dealer_info['bail_amount']),$single_price));
			}

			if($last_amount!=0){
				$usemoney = $single_price*$log_list;
			}

			M()->startTrans();
			$collection_no  = genBillsNo('SK',9);
			$colle_state =  AssetCenter::collection_log($collection_no,$usemoney,9);

			$bail = new ThriftBailService();
			$bail_state = $bail->decBail($dealer_id,$usemoney,$use_type,'查询维修保养扣款',0,0,0,$colle_state);
			if($bail_state->code !='000000'){
				$dealer_bail = false;
			}
			$bail_log =  AssetCenter::last_bail_log($dealer_id,$usemoney,$use_type);//获取最新日志log
			$clear_state = $dealer->edit(array('minus_amount'=>$last_amount)); //修改用户授权额度和可用保证金
			$pay_state = $pay_log->the_bill($usemoney,$bail_log,$log_list);  //结算操作
			if($dealer_bail){
				M()->commit();
			}else{
				M()->rollback();
			}
		}
	}
}